var group_png = '../../static/img/layers/group.png';
var image_png = '../../static/img/layers/image.png';
var imageLayer_png = '../../static/img/layers/imageLayer.png';
var label_png = '../../static/img/layers/label.png';
var lineofSight_png = '../../static/img/layers/lineofSight.png';
var location_png = '../../static/img/layers/location.png';
var point_png = '../../static/img/layers/point.png';
var pointLayer_png = '../../static/img/layers/pointLayer.png';
var polygon_png = '../../static/img/layers/polygon.png';
var polygonLayer_png = '../../static/img/layers/polygonLayer.png';
var polyline_png = '../../static/img/layers/polyline.png';
var polylineLayer_png = '../../static/img/layers/polylineLayer.png';
var terrainLayer_png = '../../static/img/layers/terrainLayer.png';
var viewshed_png = '../../static/img/layers/viewshed.png';
var eClinetY;
var app = new Vue({
    el: '#appTree',
    data: function () {
        return {
            setting: {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                },
                edit: {
                    drag: {
                        isCopy: false,
                        isMove: true,
                        prev: true,
                        next: true,
                        inner: true,
                        autoOpenTime: 0,
                        minMoveSize: 10
                    },
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false
                },
                async: {
                    enable: true
                },
                check: {
                    enable: true, //true / false 分别表示 显示 / 不显示 复选框或单选框
                    autoCheckTrigger: true, //true / false 分别表示 触发 / 不触发 事件回调函数
                    chkStyle: "checkbox", //勾选框类型(checkbox 或 radio）
                    chkboxType: {
                        "Y": "ps",
                        "N": "ps"
                    } //勾选 checkbox 对于父子节点的关联关系
                },
                callback: {
                    onCheck: this.zTreeOnCheck,
                    onDblClick: this.zTreeonDblClick,
                    onRightClick: this.zTreeOnRightClick,
                    beforeMouseDown: this.zTreeBeforeMouseDown,
                    onDrop: this.zTreeOnDrop,
                    //beforeDrag: this.zTreeBeforeDrag,
                    beforeDrop: this.zTreeBeforeDrop,
                    onExpand: this.zTreeOnExpand
                }
            },
            zNodes: window.parent.sgworld.ProjectTree.Source,
            oldTree: null,
            clickTreeNode: null,
            newAndUpdateInputValue: '',
            newOrUpdate: 0, //1 新增 2修改
            layerIndex: null,
        }
    },

    methods: {
        zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
            console.log(treeId, treeNodes, targetNode, moveType);
            if (targetNode == null || targetNode == undefined || targetNode.type == 'group' || moveType != 'inner') return true;
            else return false;
        },
        zTreeOnDrop(event, treeId, treeNodes, targetNode, moveType) {
            if (treeNodes.length == 0)
                return;
            var itemid = treeNodes[0].id;
            var groupid = 0;
            if (targetNode == null) {
                groupid = 0;
            } else {
                groupid = targetNode.id;
            }
            window.parent.sgworld.ProjectTree.changeGroup(itemid, groupid);
        },
        zTreeOnCheck(event, treeId, treeNode) {
            if (treeNode.check_Child_State < 0)
                window.parent.sgworld.ProjectTree.setVisibility(treeNode.id, treeNode.checked);

            // 同步修改数据到ProjectTree上
            window.parent.sgworld.ProjectTree.Source.forEach(item => {
                (item.id == treeNode.id) && (item.checked == treeNode.checked)
            })
        },
        zTreeonDblClick(event, treeId, treeNode) {
            if (treeNode && treeNode.id) {
                var obj = window.parent.sgworld.ProjectTree.getObject(treeNode.id);
                //上一个操作
                var cz = window.parent.sgworld.ProjectTree.starttemporaryItem();
                if (cz !== "" && (cz === "浏览边界" || cz === '街景' || cz === '地下模式')) {
                    //结束冲突事件
                    window.parent.endConflictEvent(cz);
                }
                if (treeNode.type == "Location") {
                    var position = obj._position;
                    var originalCameraLocation = {
                        destination: position.position,
                        orientation: {
                            heading: position.orientation.heading,
                            pitch: position.orientation.pitch,
                            roll: position.orientation.roll,
                        }
                    };
                    window.parent.sgworld.Navigate.flyToPointsInterest(originalCameraLocation);
                } else if (treeNode.type == "ImageryProvider") {
                    var destination = {x: -2534824.348988026, y: 9460093.258686028, z: 7094676.058819668};
                    var originalCameraLocation = {
                        destination: destination,
                        orientation: {
                            heading: 6.283185307179586,
                            pitch: -1.5707963267948966,
                            roll: 0,
                        }
                    };
                    window.parent.sgworld.Navigate.flyToPointsInterest(originalCameraLocation);
                } else {
                    window.parent.sgworld.Navigate.flyToObj(obj);
                    obj.item && window.parent.sgworld.Navigate.flyToObj(obj.item);
                    obj.item.item && window.parent.sgworld.Navigate.flyToObj(obj.item.item);
                }
            }
        },
        zTreeBeforeMouseDown(treeId, treeNode) {
            $("#rMenu").hide();
            window.parent.sgworld.ProjectTree.selectedItem = treeNode;
            if (!treeNode) {
                var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
                zTreeObj.cancelSelectedNode();
            }
        },
        zTreeOnRightClick(event, treeId, treeNode) {
            //获取弹出的高度
            eClinetY = $(window).height() - event.clientY;

            if (treeNode) {
                if (treeNode.type == 'group') {
                    this.showRMenu("group", event.offsetX + $(event.target).position().left - 20, event.offsetY + $(event.target).offset().top, treeNode.parentTId);
                } else {
                    this.showRMenu("node", event.offsetX + $(event.target).position().left - 20, event.offsetY + $(event.target).offset().top, treeNode.parentTId);
                }
            } else {
                this.showRMenu("root", event.offsetX, event.offsetY, treeNode.parentTId); //根节点
            }
            this.clickTreeNode = treeNode;
        },
        showRMenu(type, x, y, pid) {
            $("#rMenu").show();
            var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
            if (zTreeObj.getNodeByTId(pid).name === '矢量') {
                $("#m_legend").show();
                $("#m_edit").show();
            } else {
                $("#m_legend").hide();
                $("#m_edit").hide();
            }
            if (type == "root") {
                $("#m_updateName").hide();
                $("#m_addGroup").show();
                $("#m_del").hide();
                $("#m_propery").hide();
                $('#m_addLocalLayers').show();
                $('#m_addNetLayers').show();
                $('#m_addModel').show();
            } else if (type == "group") {
                $("#m_updateName").show();
                $("#m_addGroup").show();
                $("#m_del").show();
                $("#m_propery").hide();
                $('#m_addLocalLayers').show();
                $('#m_addNetLayers').show();
                $('#m_addModel').show();
            } else if (type == "node") {
                $("#m_updateName").show();
                $("#m_addGroup").hide();
                $("#m_del").show();
                $("#m_propery").show();
                $('#m_addLocalLayers').hide();
                $('#m_addNetLayers').hide();
                $('#m_addModel').hide();
            }
            var sTop;
            if (eClinetY < $("#rMenu").height()) {
                sTop = $("#rMenu").height() - eClinetY + 20;
            } else {
                sTop = 0
            }
            $("#rMenu").css({
                "top": (y - sTop) + "px",
                "left": x + "px"
            });
        },
        m_del() {
            if (this.clickTreeNode) {
                window.parent.sgworld.ProjectTree.deleteItem(this.clickTreeNode.id);
                this.clickTreeNode = null;
            }
            $("#rMenu").hide();
        },
        m_addGroupPanel() {
            this.newOrUpdate = 1;
            $("#newAndUpdateInput").show();
            $("#rMenu").hide();
        },
        m_addOrUpdate() {
            if (this.clickTreeNode) {
                if (this.newOrUpdate == 1) {
                    window.parent.sgworld.ProjectTree.createGroup(this.newAndUpdateInputValue, true, this.clickTreeNode.id);
                } else {
                    window.parent.sgworld.ProjectTree.rename(this.clickTreeNode.id, this.newAndUpdateInputValue)
                    this.clickTreeNode.name = this.newAndUpdateInputValue;
                    var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
                    zTreeObj.updateNode(this.clickTreeNode);
                }
            } else {
                if (this.newOrUpdate == 1) {
                    window.parent.sgworld.ProjectTree.createGroup(this.newAndUpdateInputValue, true, 0);
                }
            }
            $("#newAndUpdateInput").hide();
        },
        m_cancel() {
            $("#newAndUpdateInput").hide();
        },
        m_reaname() {
            this.newOrUpdate = 2;
            if (this.clickTreeNode) {
                this.newAndUpdateInputValue = this.clickTreeNode.name;
                $("#newAndUpdateInput").show();
                $("#rMenu").hide();
            }
        },
        m_propery() {
            if (this.clickTreeNode) {
                switch (this.clickTreeNode.type) {
                    case "label":
                        var tag = "Point";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2);
                        break;
                    case "ImageryProvider":
                        var tag = "ImageryProvider";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2);
                        break;
                    case "terrain":
                        var tag = "terrain";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2);
                        break;
                    case "Imagelabel":
                        var tag = "Point";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "polylineVolumeLayer":
                        var tag = "Point";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入sessionpolylineWallLayer
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "polylineWallLayer":
                        var tag = "Point";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入sessionpolylineWallLayer
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "Imagelabel":
                        var tag = "Point";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "polygon":
                        var tag = "TwoDimensional";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "pointLayer":
                        var tag = "TwoDimensional";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "3DTilesets":
                        var tag = "TwoDimensional";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "polygonLayer":
                        var tag = "TwoDimensional";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "Streetscape":
                        var tag = "Streetscape";
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                        break;
                    case "polylineLayer":
                        var tag = "";
                        if (this.clickTreeNode.style.layertype != undefined && this.clickTreeNode.style.layertype == "Streetscape") {
                            tag = "Streetscapes";
                        } else {
                            tag = "WfsLayer";
                        }
                        var itemid = this.clickTreeNode.id;
                        var type = this.clickTreeNode.type;
                        sessionStorage.setItem('tag', tag);//数据存入session
                        sessionStorage.setItem('itemid', itemid);//数据存入session
                        sessionStorage.setItem('type', type);//数据存入session
                        window.parent.fnPropsOpen('图层属性', 'components/Layers/propLayer', 350, 540, 2)
                    default:
                        break;
                }
                $("#rMenu").hide();
            }
        },
        m_legend() {
            $("#rMenu").hide();
            var itemid = this.clickTreeNode.id;
            var type = this.clickTreeNode.type;
            //sessionStorage.setItem('tag',tag);//数据存入session
            sessionStorage.setItem('itemid', itemid);//数据存入session
            sessionStorage.setItem('type', type);//数据存入session
            window.parent.selDataIndex = this.layerIndex = window.parent.layer.open({
                title: '图例',
                type: 2,
                skin: 'other-class',
                area: ['600px', '255px'],
                content: 'components/Layers/legend.html',
                // content: {
                //     content: SelectLayer,
                //     parent: this,
                //     data: []
                // },
                shade: false,
                shadeClose: false
            });
        },
        m_edit() {
            //矢量数据修改
            var itemid = this.clickTreeNode.id;
            var layerw = window.parent.sgworld.ProjectTree.getObject(itemid);
            if (layerw.item == undefined) {
                return;
            }
            try {
                layerw.setRefresh(false);
            } catch (ex) {
            }
            window.parent.sgworld.Creator.createVectorEditing();
        },
        m_newLocalLayer() {
            $("#files").click();
            $("#rMenu").hide();
        },
        m_newNetLayer() {
            $("#rMenu").hide();
            window.parent.selDataIndex = this.layerIndex = window.parent.layer.open({
                title: '选择数据源',
                type: 2,
                skin: 'other-class',
                area: ['600px', '255px'],
                content: 'components/Layers/selectLayer.html',
                // content: {
                //     content: SelectLayer,
                //     parent: this,
                //     data: []
                // },
                shade: false,
                shadeClose: false
            });
        },
        fileInputExp() {
            // this.fileImport();
            var selectedFile = document.getElementById('files').files[0];
            var name = selectedFile.name; //读取选中文件的文件名
            var size = selectedFile.size; //读取选中文件的大小
            //console.log("文件名:"+name+"大小:"+size);
            var reader = new FileReader(); //这是核心,读取操作就是由它完成.
            reader.readAsText(selectedFile); //读取文件的内容,也可以读取文件的URL
            reader.onload = function () {
                //当读取完成后回调这个函数,然后此时文件的内容存储到了result中,直接操作即可
                //console.log(this.result);
                window.parent.sgworld.Creator.createGeoJsonFeatureLayer("", JSON.parse(this.result), {}, 0, function (source) {
                    window.parent.sgworld.Navigate.flyToObj(source);
                });
            }
        },
        m_newModel() {
            $("#rMenu").hide();
            this.layerIndex = window.parent.layer.open({
                title: '选择数据源',
                type: 2,
                content: {
                    content: SelectLayer,
                    parent: this,
                    data: []
                },
                shade: false,
                shadeClose: false
            });
        },
        m_export() {
            //导出工程树
            window.parent.sgworld.ProjectTree.export();
        },
        m_newLocation() {
            $("#rMenu").hide();
            var position = window.parent.sgworld.Navigate.getPosition();
            position = window.parent.sgworld.Coordinate.Cartesian3_to_WGS84(position);
            var originalCameraLocation = {
                position: window.parent.sgworld.Viewer.camera.position.clone(),
                orientation: {
                    heading: window.parent.sgworld.Viewer.camera.heading,
                    pitch: window.parent.sgworld.Viewer.camera.pitch,
                    roll: window.parent.sgworld.Viewer.camera.roll,
                }
            }
            window.parent.sgworld.Creator.createLocation("新建兴趣点", originalCameraLocation, 0);
            //window.parent.sgworld.Creator.createLocation("新建兴趣点", [position.longitude, position.latitude, position.height], 0);
        },
        fileImport() {
            //获取读取我文件的File对象
        },
        handleCloseLayer() {
            this.Layer.close(this.layerIndex);
        },
        zTreeOnExpand(event, treeId, treeNode) {
            $('#' + treeNode.tId).find('.node_name').css('font-size', parent.configStyle.fontSize + 'px')
        },
        getIcon(item) {
            switch (item.type) {
                case "label":
                    item.icon = label_png;
                    break;
                case "Imagelabel":
                    item.icon = image_png;
                    break;
                case "group":
                    item.icon = group_png;
                    break;
                case "polyline":
                    item.icon = polyline_png;
                    break;
                case "polygon":
                    item.icon = polygon_png;
                    break;
                case "polygonLayer":
                    item.icon = polygonLayer_png;
                    break;
                case "Location":
                case "Point":
                    item.icon = location_png;
                    break;
                case "imageLayer":
                    item.icon = imageLayer_png;
                    break;
                case "pointLayer":
                    item.icon = pointLayer_png;
                    break;
                default:
                    break;
            }
        }
    },
    watch: {
        zNodes: {
            handler: function (newVal, oldVal) {
                var addDif = _.difference(newVal, this.oldTree);
                var delDif = _.difference(this.oldTree, newVal);
                var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
                var _this = this;
                _.forEach(addDif, function (value) {
                    if (value) {
                        //获取他的父级增加勾选状态
                        if (value.pId) {
                            for (var i = 0, l = _this.oldTree.length; i < l; i++) {
                                if (value.pId == _this.oldTree[i].id) {
                                    var node = zTreeObj.getNodeByParam("id", _this.oldTree[i].id);
                                    node.checked = true;
                                    zTreeObj.updateNode(node);
                                    break;
                                }
                            }
                        }
                        value.checked = true;
                        _this.getIcon(value);
                        var node = zTreeObj.getNodeByParam("id", value.pId);
                        zTreeObj.addNodes(node, value);
                        $('.node_name').css('font-size', parent.configStyle.fontSize + 'px');
                    }
                });
                _.forEach(delDif, function (value) {
                    if (value) {
                        var node = zTreeObj.getNodeByParam("id", value.id);
                        zTreeObj.removeNode(node);
                    }
                });
                this.oldTree = _.clone(newVal);
            }
        },

    },
    mounted() {
        this.$nextTick(function () {
            this.oldTree = _.clone(this.zNodes);
            for (var i = 0; i < this.zNodes.length; i++) {
                this.getIcon(this.zNodes[i]);
            }
            $.fn.zTree.init($("#treeDemo"), this.setting, this.zNodes);
            window.parent.projectTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
            // console.log(this.zNodes,this.$store.state.treeInitData)
            /*  if(this.$store.state.treeInitData){
                var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
                //zTreeObj.checkAllNodes(false);

                this.$store.dispatch('UpdateTreeInitData',false)
              }*/
            $('.node_name').css('font-size', '12px');
            $('#rMenu li').css('font-size', '12px');
        });
        var _this = this;
        //window.parent.EventEmitter
        window.EventEmitter.$on(eventName.OPEN_SELECTLAYERANDADRESS_FN, function (netLayerAdress, layerType, dataSource, loadType, layer) {
            if (layerType == "geojson")
                window.parent.sgworld.Creator.createGeoJsonFeatureLayer("", netLayerAdress, {}, 0, function (source) {
                    window.parent.sgworld.Navigate.flyToObj(source);
                });
            else if (layerType == "image") {
                if (dataSource == "arcgis" && loadType == "wms") {
                    window.parent.sgworld.Creator.createArcGisImageryLayer("新建影像图层", {
                        url: netLayerAdress,
                        layer: layer
                    })
                }
                if (dataSource == "arcgis" && loadType == "wmts") {
                    window.parent.sgworld.Creator.createWebMapTileServerImageLayer("新建影像图层", {
                        url: netLayerAdress,
                        layer: layer
                    })
                } else if (dataSource == "geoserver" && loadType == "wms") {
                    window.parent.sgworld.Creator.createWebMapServerImageLayer("新建影像图层", {
                        url: netLayerAdress,
                        layer: layer
                    })
                } else if (dataSource == "geoserver" && loadType == "wmts") {
                    window.parent.sgworld.Creator.createWebMapTileServerImageLayer("新建影像图层", {
                        url: netLayerAdress,
                        layer: layer
                    })
                } else if (dataSource == "other" && loadType == "wms") {
                    window.parent.sgworld.Creator.createWebMapServerImageLayer("新建影像图层", {
                        url: netLayerAdress,
                        layer: layer
                    })
                } else if (dataSource == "other" && loadType == "wmts") {
                    window.parent.sgworld.Creator.createWebMapTileServerImageLayer("新建影像图层", {
                        url: netLayerAdress,
                        layer: layer
                    })
                }
            } else if (layerType == "model") {
                var tilesets = window.parent.sgworld.Creator.create3DTilesets("", netLayerAdress, 0, "");
                window.parent.sgworld.Navigate.flyToObj(tilesets);
            }
        });
        //window.parent.EventEmitter
        window.EventEmitter.$on(eventName.CLOSE_SELECTLAYERANDADRESS_FN, function () {
            window.parent.layer.close(_this.layerIndex);
        });
        $('#rMenu').css('background-color', "#ffff00");

    }

})
